package com.citycloud.ccuap.tc.admin.filter;

import com.citycloud.ccuap.tc.admin.constant.AdminConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求参数滤波器：oauth2的access_token非请求参数时，添加至传参中以便AccessDecisionManager获取相应认证信息
 *
 * @date 2020/07/07
 */
public class RequestParameterFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String accessToken = StringUtils.isEmpty(request.getParameter(AdminConstant.TOKEN_KEY))
                ? request.getParameter(AdminConstant.ACCESS_TOKEN_KEY)
                : request.getParameter(AdminConstant.TOKEN_KEY);
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = StringUtils.isEmpty(request.getHeader(AdminConstant.TOKEN_KEY))
                    ? request.getHeader(AdminConstant.ACCESS_TOKEN_KEY)
                    : request.getHeader(AdminConstant.TOKEN_KEY);
        }

        if (StringUtils.isEmpty(request.getParameter(AdminConstant.ACCESS_TOKEN_KEY)) && StringUtils.isNotBlank(accessToken)) {
            HeaderRequestWrapper requestWrapper = new HeaderRequestWrapper(request);
            requestWrapper.addParameter(AdminConstant.ACCESS_TOKEN_KEY, accessToken);
            filterChain.doFilter(requestWrapper, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
